//
//  LgImageColorModel.m
//  InfiniteLoop
//
//  Created by HJY on 2018/12/14.
//  Copyright © 2018年 LG. All rights reserved.
//

#import "LgImageColorModel.h"
#import <SOZOChromoplast/SOZOChromoplast.h>
#import <SDWebImage/SDWebImageDownloader.h>

@implementation LgImageColorModel

-(void)setImageName:(NSString *)imageName {
    _imageName = imageName;
    
    _downloadImage = [UIImage imageNamed:imageName];
    SOZOChromoplast *list = [[SOZOChromoplast alloc] initWithImage:_downloadImage];
    _imageColor = list.dominantColor;
}

-(void)setImageURLString:(NSString *)imageURLString {
    _imageURLString = imageURLString;
    
    if ([imageURLString hasPrefix:@"http://"] || [imageURLString hasPrefix:@"https://"]) {
        NSURL *URL = [[NSURL alloc] initWithString:imageURLString];
        [SDWebImageDownloader.sharedDownloader downloadImageWithURL:URL options:SDWebImageDownloaderUseNSURLCache progress:^(NSInteger receivedSize, NSInteger expectedSize, NSURL * _Nullable targetURL) {
            
        } completed:^(UIImage * _Nullable image, NSData * _Nullable data, NSError * _Nullable error, BOOL finished) {
            if (image != nil) {
                SOZOChromoplast *list = [[SOZOChromoplast alloc] initWithImage:image];
                self.imageColor = list.dominantColor;
                self.downloadImage = image;
            }
        }];
    }
}

-(void)setImageColor:(UIColor *)imageColor {
    _imageColor = imageColor;
    
}

-(void)setDownloadImage:(UIImage *)downloadImage {
    _downloadImage = downloadImage;
}

// 图片不存在就下载
-(UIColor *)downloadNetworkImage {
    
    if ([_imageURLString hasPrefix:@"http://"] || [_imageURLString hasPrefix:@"https://"]) {
        NSURL *URL = [[NSURL alloc] initWithString:_imageURLString];
        NSData *data = [[NSData alloc] initWithContentsOfURL:URL];
        UIImage *image = [[UIImage alloc] initWithData:data];
        SOZOChromoplast *list = [[SOZOChromoplast alloc] initWithImage:image];
        self.imageColor = list.dominantColor;
        self.downloadImage = image;
        return list.dominantColor;
    }
    return [UIColor clearColor];
}

// 如果是本地图片  _imageColor没有值时  调用此方法 重新获取
-(UIColor*)getImageColor {
    
    SOZOChromoplast *list = [[SOZOChromoplast alloc] initWithImage: _downloadImage];
    _imageColor = list.dominantColor;
    return _imageColor;
}

@end
